package com.learn.rpc.version.version3;

import com.learn.rpc.common.AdminUser;
import com.learn.rpc.common.FinalParam;
import com.learn.rpc.common.IAdminUserService;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * 使用简单代理的方式去实现远程调用,将对象通过代理的方式进行创建,在代理的使用中进行socket远程调用
 * 该实现为简单实现,并不能进行所有方法适配,仅仅适配了findAdminUserById(int)方法的调用
 * @author wangxing
 * @version 2020/8/15 7:03 Administrator
 */
public class RpcClient {
    public static void main(String[] args) throws IOException {
       IAdminUserService service = Stud.getStudIAdminUserService();
        System.out.println(service.findAdminUserById(12553));
    }
}

class Stud {
    static InvocationHandler h = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Socket socket = new Socket(FinalParam.HOST,FinalParam.PORT);

            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.writeInt((Integer) args[0]);
            dataOutputStream.flush();

            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            AdminUser adminUser = (AdminUser) objectInputStream.readObject();
            objectInputStream.close();
            dataOutputStream.close();
            socket.close();

            return adminUser;
        }
    };
    public static IAdminUserService getStudIAdminUserService() {
        IAdminUserService service = (IAdminUserService) Proxy.newProxyInstance(IAdminUserService.class.getClassLoader(),new Class[]{IAdminUserService.class},h);
        return service;
    }
}
